package org.lc.platform.redis.component;

import lombok.extern.slf4j.Slf4j;
import org.lc.platform.redis.dto.MessageDto;
import org.lc.platform.redis.service.CacheService;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Slf4j
@Component
public class RedisPublisher {

    private final CacheService cacheService;
    private final DefaultRedisScript<Long> luaScript;

    public RedisPublisher(CacheService cacheService) {
        this.cacheService = cacheService;
        this.luaScript = new DefaultRedisScript<>();
        luaScript.setScriptText("if redis.call('setnx', KEYS[1], ARGV[1]) == 1 then return 1 else return 0 end");
        luaScript.setResultType(Long.class);
    }

    /**
     * 相同的消息只推送一次防止重复推送
     * {channel}
     * {message}
     */
    public void sendOnceMessage(String channel, MessageDto message) {
        Long result = cacheService.getRedis().execute(luaScript, Collections.singletonList(channel), Collections.singleton(message));
        if (result != null && result.equals(1L)) {
            cacheService.getRedis().convertAndSend(channel, message);
        }
    }
    public void sendMessage(String channel, MessageDto message) {
        cacheService.getRedis().convertAndSend(channel, message);
    }
}